<template>
  <div style="position: relative">
    <el-form
      :inline="true"
      size="mini"
      :model="formInline"
      label-position="right"
    >
      <el-form-item label="线索名称">
        <el-input
          class="filter-item"
          v-model="formInline.clueName"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="企业名称">
        <el-input
          class="filter-item"
          v-model="formInline.customerName"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="线索来源">
        <el-select
          v-model="formInline.clueSource"
          placeholder="请选择"
        >
          <el-option
            v-for="item in clueSourceList"
            :key="item.value"
            :label="item.label"
            :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型">
        <el-select
          v-model="formInline.businessType"
          placeholder="请选择"
          @change="handleSelectBusinessType"
        >
          <el-option
            v-for="item in businesstypeTree"
            :key="item.id"
            :label="item.businessName"
            :value="item.idStr">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="企业联系电话">
        <el-input
          class="filter-item"
          v-model="formInline.telephone"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="times"
          type="daterange"
          align="right"
          unlink-panels
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          @change="selecttime"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="线索状态">
        <el-select
          v-model="formInline.clueStatus"
          placeholder="请选择"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="待转商机" value="0"></el-option>
          <el-option label="已转商机" value="1"></el-option>
          <el-option label="待立项" value="2"></el-option>
          <el-option label="已立项" value="3"></el-option>
          <el-option label="已完成" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="warning"
          class="el-button--reset"
          icon="el-icon-refresh-right"
          @click="resetFromdata"
          size="mini"
        ></el-button>
        <el-button type="primary" size="mini" @click="onSubmit">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="addFromdata"
          >创建线索</el-button
        >
        <el-button type="primary" size="mini" @click="exportForm"
          >导出</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="handleClickImport"
          >导入</el-button
        >
      </el-form-item>
    </el-form>
    <el-row>
      <el-col :span="24">
        <div class="total">
          <div class="total-item" :class="{'active': !clueStatus}" @click="handleClickTotal('')">全部（{{ countInfo.qb || 0 }}）</div>
          <div class="total-item" :class="{'active': clueStatus === '1'}" @click="handleClickTotal('1')">已转商机（{{ countInfo.yzsj || 0 }}）</div>
          <div class="total-item" :class="{'active': clueStatus === '2'}" @click="handleClickTotal('2')">待立项（{{ countInfo.dlx || 0 }}）</div>
          <div class="total-item" :class="{'active': clueStatus === '4'}" @click="handleClickTotal('4')">已完成（{{ countInfo.ywc || 0 }}）</div>
        </div>
        <el-table
          :data="tableData"
          size="mini"
          style="width: 100%"
          header-cell-class-name="table-header-gray"
          v-loading="isShowloading"
        >
          <el-table-column
            type="index"
            align="center"
            width="55"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="clueName"
            align="center"
            sortable
            label="线索名称"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="businessTypeName"
            align="center"
            label="业务类型"
            sortable
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="customerName"
            align="center"
            sortable
            label="企业名称"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="contacts"
            align="center"
            sortable
            label="企业联系人"
            width="120"
          ></el-table-column>
          <el-table-column
            prop="telephone"
            align="center"
            sortable
            label="企业联系电话"
            width="120"
          ></el-table-column>
          <el-table-column
            prop="clueStatus"
            align="center"
            label="线索状态"
            sortable
            show-overflow-tooltip
          >
            <template slot-scope="{ row }">
              <span :style="{ color: clueStatusColor[row.clueStatus] }">{{
                row.clueStatus | statusFilter
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="clueSource"
            align="center"
            label="线索来源"
            sortable
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="createUserName"
            align="center"
            label="创建人"
            sortable
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="createTime"
            align="center"
            label="创建时间"
            sortable
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column label="操作" fixed="right" width="260">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="handleEdit(scope.row)"
                v-if="(scope.row.clueStatus === 0 || scope.row.clueStatus === 1) && scope.row.createUser === userId"
                >编辑</el-button
              >
              <el-button type="text" @click="handleInfo(scope.row)"
                >查看</el-button
              >
              <el-button type="text" @click="handleInfo(scope.row, 1)" v-if="scope.row.clueStatus === 0 || scope.row.clueStatus === 1 || scope.row.clueStatus === 1"
                >更新动态</el-button
              >
              <el-button
                type="text"
                v-if="scope.row.clueStatus === 0"
                @click="handleTurn(scope.row)"
                >转商机</el-button
              >
              <el-button
                type="text"
                @click="handleDelete(scope.row)"
                v-if="scope.row.clueStatus === 0 && scope.row.createUser === userId"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="margin-top: 10px">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNo"
            :page-size="page_size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            :total="total"
          ></el-pagination>
        </el-row>
      </el-col>
    </el-row>
    <el-dialog
      title="用户导入"
      :visible.sync="showImport"
      width="400px"
      :close-on-click-modal="false"
      append-to-body
    >
      <el-upload
        class="upload-demo"
        ref="upload-demo"
        accept=".xls,.xlsx"
        :limit="1"
        drag
        :action="upload.url"
        :headers="upload.headers"
        :on-change="changeFile"
        :on-success="handleFileSuccess"
        :show-file-list="false"
        :data="{ fieldName: '123' }"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="handleClickTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
    </el-dialog>
    <el-dialog
      title="导入失败"
      :visible.sync="showFail"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div style="max-height: 500px; overflow-y: auto">
        <el-table
          :data="failList"
          size="mini"
          style="width: 100%"
          header-cell-class-name="table-header-gray"
          v-loading="isShowloading"
        >
          <el-table-column
            type="index"
            align="center"
            width="55"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="clueName"
            align="center"
            label="线索名称"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="businessTypeName"
            align="center"
            label="业务类型"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="customerName"
            align="center"
            label="企业名称"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="contacts"
            align="center"
            label="企业联系人"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="telephone"
            align="center"
            label="联系电话"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="clueSource"
            align="center"
            label="线索来源"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="reason"
            align="center"
            label="失败原因"
            show-overflow-tooltip
          ></el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Cluemanagement } from '@/api/commercial.js';
import { Businesstype } from '@/api/business.js';
import Clueadd from './Clueadd.vue';
import { getToken } from '@/utils';
import requestUrl from '@/core/http/requestUrl';
export default {
  name: 'Cluemanagement',
  filters: {
    statusFilter (val) {
      const data = {
        0: '待转商机',
        1: '已转商机',
        2: '待立项',
        3: '已立项',
        4: '已完成'
      };
      return data[val];
    }
  },
  data () {
    return {
      clueSourceList: [
        {value: '0', label: '电话来访'},
        {value: '1', label: '客户介绍'},
        {value: '2', label: '独立开发'},
        {value: '3', label: '社会公开信息'},
        {value: '4', label: '其他'}
      ],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url: requestUrl('admin/clue/upExport')
      },
      clueStatusColor: {
        0: '#409EFF',
        1: '#444',
        2: '#444',
        3: '#F56C6C',
        4: '#67C23A'
      },
      businesstypeTree: [],
      businesstypeId: [],
      businesstProps: {
        value: 'id',
        label: 'businessName',
        children: 'children',
        checkStrictly: true
      },
      // 线索转商机权限标识
      clueToOppoAuth: false,
      editDialogVisible: false,
      formInline: {
        clueName: null,
        customerName: null,
        contacts: null,
        startCreateTime: null,
        endCreateTime: null,
        businessType: null,
        clueStatus: null,
        clueSource: null,
        telephone: null
      },
      tableData: [],
      total: 0,
      page_size: 10,
      pageNo: 1,
      isShowloading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick (picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }
        ]
      },
      times: '',
      showImport: false,
      failList: [],
      showFail: false,
      countInfo: {},
      userId: '',
      clueStatus: ''
    };
  },
  created () {},
  mounted () {
    this.loadClueWidgetData();
    this.loadbusinesstypeTree();
    this.loadClueToOppoAuth();
  },
  activated () {
    this.loadClueWidgetData(); // 数据加载的方法
  },
  computed: {},
  methods: {
    // 获取业务类型
    handleSelectBusinessType (val) {
      console.log(val)
      // this.$set(this.ruleForm, 'businessType', val.join(','))
      // this.ruleForm.businessType = val.join(',')
      this.formInline.businessType = val
    },
    changeFile (file) {},
    handleFileSuccess (res) {
      console.log(res);
      this.$refs['upload-demo'].clearFiles();
      if (res.data.failCount > 0) {
        this.failList = res.data.fail;
        this.showImport = false;
        this.showFail = true;
      } else {
        this.resetFromdata();
        this.showImport = false;
        this.$message({
          message: `导入成功${res.data.success}条`,
          type: 'success',
          duration: 5000
        });
      }
    },
    handleClickTemplate () {
      return new Promise((resolve, reject) => {
        Cluemanagement.ExportTemplate(this, {}, '线索导入模板.xlsx');
      });
    },
    handleClickImport () {
      this.showImport = true;
    },
    // 选择创建时间
    selecttime (times) {
      if (times) {
        this.formInline.startCreateTime = times[0];
        this.formInline.endCreateTime = times[1];
      } else {
        this.formInline.startCreateTime = '';
        this.formInline.endCreateTime = '';
      }
    },
    /**
     * 业务类型信息表树形列表
     */
    loadbusinesstypeTree () {
      return new Promise((resolve, reject) => {
        Businesstype.tree(this)
          .then((res) => {
            this.businesstypeTree = res.data;
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    businessChange () {
      let info = this.businesstypeId;
      let length = info.length - 1;
      this.formInline.businessType = info[length];
      this.$refs['ref_business'].dropDownVisible = false;
    },
    loadClueToOppoAuth () {
      return new Promise((resolve, reject) => {
        Cluemanagement.checkClueToOppo(this)
          .then((res) => {
            this.clueToOppoAuth = res.data;
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    handleClickTotal (val) {
      this.formInline.clueStatus = val
      this.clueStatus = val
      this.pageNo = 1;
      this.loadClueWidgetData()
    },
    /**
     * 线索列表
     */
    loadClueWidgetData () {
      let params = {
        ...this.formInline,
        size: this.page_size,
        current: this.pageNo
      };
      return new Promise((resolve, reject) => {
        Cluemanagement.list(this, params)
          .then((res) => {
            if (!res.data) return
            this.countInfo = res.data.count;
            this.userId = res.data.userId
            if (!res.data.data) return
            this.tableData = res.data.data.records;
            this.total = res.data.data.total;
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    // 搜索
    onSubmit () {
      this.pageNo = 1;
      this.loadClueWidgetData();
    },
    // 重置
    resetFromdata () {
      this.formInline = {
        clueName: null,
        customerName: null,
        contacts: null,
        startCreateTime: null,
        endCreateTime: null,
        businessType: null,
        clueStatus: null,
        clueSource: null,
        telephone: null
      };
      this.times = '';
      this.clueStatus = ''
      this.pageNo = 1;
      this.page_size = 10;
      this.loadClueWidgetData();
    },
    // 分页导航
    handleCurrentChange (val) {
      this.pageNo = val;
      this.loadClueWidgetData();
    },
    handleSizeChange (val) {
      this.page_size = val;
      this.loadClueWidgetData();
    },
    currentChange (val) {
      this.pageNo = val;
      this.loadClueWidgetData();
    },
    // 创建线索
    addFromdata () {
      let params = {};
      this.$dialog
        .show(
          '新建',
          Clueadd,
          {
            area: '800px'
          },
          params
        )
        .then((res) => {
          this.loadClueWidgetData();
        })
        .catch((e) => {});
    },
    // 导出
    exportForm () {
      let params = {
        ...this.formInline,
        size: this.page_size,
        current: this.pageNo
      };
      return new Promise((resolve, reject) => {
        Cluemanagement.ExportFile(this, params, '线索管理明细表.xlsx');
      });
    },
    // 查看
    handleInfo (row, type) {
      this.$router.push({
        path: '/CluemanagementDetail',
        query: {
          clueId: row.id,
          type
        }
      });
    },
    // 修改
    handleEdit (row) {
      this.$dialog
        .show(
          row ? '编辑线索' : '新建线索',
          Clueadd,
          {
            area: '800px'
          },
          {
            clueId: row.id
          }
        )
        .then((res) => {
          this.loadClueWidgetData();
        })
        .catch((e) => {});
    },
    // 转商机
    handleTurn (row) {
      this.$router.push({
        path: '/Opportunitiesadd',
        query: {
          clueId: row.id
        }
      });
    },
    // 删除
    handleDelete (row) {
      this.$confirm('确定要删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let params = row.id;
        return new Promise((resolve, reject) => {
          Cluemanagement.delete(this, params)
            .then((res) => {
              this.loadClueWidgetData();
            })
            .catch((e) => {
              reject(e);
            });
        });
      });
    }
  }
};
</script>
<style scoped lang="scss">
.total {
  display: flex;
  align-items: center;
  .total-item {
    padding: 10px;
    cursor: pointer;
    transition: color 0.3s;
    &:hover {
      color: #409EFF;
    }
  }
  .active {
    color: #409EFF;
  }
}
</style>
